package com.glory.good_dark.activity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONPObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.good_dark.R;
import com.glory.good_dark.adapter.MaterielListAdapter;
import com.glory.good_dark.adapter.NormalPopListAdapter;
import com.glory.good_dark.application.App;
import com.glory.good_dark.callback.StringCallback;
import com.glory.good_dark.entity.EqpLotIDEntity;
import com.glory.good_dark.entity.LotIDInfoEntity;
import com.glory.good_dark.entity.PDALotidTrankInEntity;
import com.glory.good_dark.entity.response.BaseEntity;
import com.glory.good_dark.utils.MyUtils;
import com.glory.good_dark.utils.NetUtils;
import com.glory.good_dark.utils.PopUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils.getConfirmAndCancelDialog;


/**
 * @author yi.zhang
 * @date 2019/6/13
 * @desc 多批开始作业
 */
public class MultiBatchStartActivity extends BaseProjectActivity {
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.lot_Txt)
    TextView lotTxt;
    @BindView(R.id.product_Txt)
    TextView productTxt;
    @BindView(R.id.number_Txt)
    TextView numberTxt;
    @BindView(R.id.tvEqpStatus)
    TextView tvEqpStatus;
    @BindView(R.id.materiel_Rv)
    RecyclerView materielRv;
    @BindView(R.id.adjustable_But)
    Button btnAdjustable;
    @BindView(R.id.EQPID_Txt)
    TextView EQPIDTxt;
    @BindView(R.id.process)//工序
            TextView process;
    @BindView(R.id.process_Txt)//运输筐
            TextView tvProcess;
    @BindView(R.id.tvLotID)//已上线批次：内框
            TextView tvLotID;
    @BindView(R.id.ivLotIDListArrow)//已上线批次：下拉图标
            ImageView ivLotIDListArrow;
    @BindView(R.id.flLotIDList)//已上线批次：外框
            FrameLayout flLotIDList;
    @BindView(R.id.etWafer)
    EditText etWafer;
    @BindView(R.id.llWaferLayout)
    LinearLayout llWaferLayout;
    @BindView(R.id.rvWaferList)
    RecyclerView rvWaferList;
    private List<String> lotIDList;//已上线批次：
    private String Onlotid = "";
    private FreeUI_GeneralPop lotIDPop;

    private FreeUI_GeneralFragmentDialog dialog;
    private LotIDInfoEntity lotIDInfoEntity;
    private MaterielListAdapter materielListAdapter;
    private int PROCESS_CRR = 0;
    private BaseQuickAdapter<String,BaseViewHolder> adapter;

    @Override
    protected void EQPReplaceSuccess(int tag, String content) {
        if (tag == PROCESS_CRR) {
            tvProcess.setText(content);
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_multibatchstart;
    }

    @Override
    protected void initView() {
        EQPIDTxt.setText(App.EQPID);
        lotIDList = new ArrayList<>();//已上线批次：
        initRecyclerView(materielRv, this);
        initRecyclerView(rvWaferList, this);
        materielListAdapter = new MaterielListAdapter(null, false);
        materielListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielListAdapter.isFirstOnly(true);
        materielRv.setAdapter(materielListAdapter);
        adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.adapter_wafer, null) {
           @Override
           protected void convert(BaseViewHolder helper, String item) {
                helper.setText(R.id.tvContent,item);
           }
       };
       adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
       adapter.isFirstOnly(true);
       rvWaferList.setAdapter(adapter);
       adapter.setOnItemClickListener((adapter1, view, position) -> FreeApi_DialogUtils.getConfirmAndCancelDialog(MultiBatchStartActivity.this, "是否删除当前wafer信息", new FreeUI_CommonCallback() {
           @Override
           public void onSuccess() {
               adapter1.remove(position);
           }
       }, () -> {
       }).show(getSupportFragmentManager(),"DELETE_DIALOG"));

        MyUtils.setEditTextListener(etWafer, this, s -> {
                   if (!adapter.getData().contains(s)){
                       adapter.addData(s);
                       etWafer.setText("");
                       etWafer.requestFocus();
                   }else {
                       showToast("当前Wafer已在列表中",false);
                   }
        });

    }

    //LotIDInfoEntity//EqpLotIDEntity
    @Override
    protected void initData() {
        FreeUI_EntityCallBack<BaseEntity<EqpLotIDEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<EqpLotIDEntity>>
                (new TypeToken<BaseEntity<EqpLotIDEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<EqpLotIDEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), getSupportFragmentManager())) {
                    tvEqpStatus.setText(response.body().getData().getBody().getEQP_RUN_STATE());//设备状态
                    List<EqpLotIDEntity.LotIDListEntity> MultiBatchStartLotids = response.body().getData().getBody().getEQP_RUN_LOTIDLIST();
                    lotIDList.clear();
                    if (MultiBatchStartLotids.size() > 0) {
                        for (EqpLotIDEntity.LotIDListEntity entity : MultiBatchStartLotids) {
                            lotIDList.add(entity.getLOT_STATE() + "/" + entity.getLOT_ID());//拼接 批次状态/批次号
                            //showToast("获得多批信息："+lotIDList.size(),false);
                        }
                    } else {
                        //showToast("当前设备无已上线批次号",false);
                        //MultiBatchStartActivity.this.finish();// 关闭了窗体
                    }
                }
//                if (response.body().isSuccess(MultiBatchStartActivity.this,getSupportFragmentManager(),true)) {
//                    tvEqpStatus.setText(response.body().getData().getBody().getEQP_RUN_STATE());
//                    List<EqpLotIDEntity.LotIDListEntity> lotList = response.body().getData().getBody().getEQP_RUN_LOTLIST();
//                    if (lotList.size() <= 0){
//                        return;
//                    }
//                }


            }

            @Override
            public void onError
                    (Response<BaseEntity<EqpLotIDEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDAGetEqpLotidList");
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("EQP_ID", App.EQPID);
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDAGetEqpLotidList", jsonObject);

    }


    @Override
    protected void onRestart() {
        super.onRestart();
        //重新回到当前页面不需要刷新数据
//        getLotInfo(lotTxt.getText().toString());
    }

    private void fillLotData() {
        lotTxt.setText(lotIDInfoEntity.getLOT_ID());
        productTxt.setText(lotIDInfoEntity.getPART_NAME());
        numberTxt.setText(String.valueOf(lotIDInfoEntity.getINPUT_QTY()));
        process.setText(lotIDInfoEntity.getPROCESS());
        tvProcess.setText(lotIDInfoEntity.getTRACKIN_CRR_ID());
        materielListAdapter.setNewData(lotIDInfoEntity.getMES_MAT_LIST());
        tvLotID.setText("");//
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("批次开始操作");
        freeUI_titleView.setRightListener("开始作业", v -> {
            if (lotIDInfoEntity == null) {
                return;
            }
            if (lotIDInfoEntity.getTRACKIN_PROCESS_CRR().equals("1") || lotIDInfoEntity.getTRACKOUT_PROCESS_CRR().equals("1")) {
                if (tvProcess.getText().toString().equals("")) {
                    showToast("请输入或扫描运输筐号", false);
                    return;
                }
            }
            if (lotTxt.getText().toString().equals("")) {
                showToast("请输入或扫描批次信息", false);
            } else if (EQPIDTxt.getText().toString().equals("")) {
                showToast("请输入或扫描设备信息", false);
                finish();
            } else if (lotIDInfoEntity.getPROCESS().equals("Q040")) {
                getConfirmAndCancelDialog(this, "是否调整轨道", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        submit(lotTxt.getText().toString(), EQPIDTxt.getText().toString(), 1);
                    }
                }, () -> submit(lotTxt.getText().toString(), EQPIDTxt.getText().toString(), 0)).show(getSupportFragmentManager(), "");
            } else {
                submit(lotTxt.getText().toString(), EQPIDTxt.getText().toString(), 2);
            }
        });
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    private void getLotInfo(String lotID) {
//        String ss = "{\n" +
//                "    \"data\":{\n" +
//                "        \"HEADER\":{\n" +
//                "            \"MACHINENAME\":\"PDA-MT9001\",\n" +
//                "            \"MESSAGENAME\":\"PDAEQPInfo\",\n" +
//                "            \"TRANSACTIONID\":\"c5e5e318-389d-4c39-b914-e4c10ba519d4\",\n" +
//                "            \"EVENTTIME\":\"2019-03-16 16:28:59.585\"\n" +
//                "        },\n" +
//                "        \"BODY\":{\n" +
//                "            \"LOT_ID\":\"TS00001\",\n" +
//                "            \"EQP_ID\":\"LC128\",\n" +
//                "            \"EQP_NAME\":\"AD125\",\n" +
//                "            \"EQP_TYPE\":\"TS00001\",\n" +
//                "            \"EQP_RUN_STATE\":\"运行中\",\n" +
//                "            \"EQP_RUN_STATE_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"PART_NAME\":\"产品名称\",\n" +
//                "            \"INPUT_QTY\":2100,\n" +
//                "            \"START_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"END_TIME\":\"2019-03-16 16:28:59\",\n" +
//                "            \"RECIPE_NAME\":\"AD125\",\n" +
//                "            \"ID\":333,\n" +
//                "            \"RUN_ID\":102,\n" +
//                "            \"PROCESS\":\"P080\",\n" +
//                "            \"REMARK\":\"   \",\n" +
//                "            \"TRACKIN_PROCESS_CRR\":\"0\",\n" +
//                "            \"TRACKIN_CRR_ID\":\"TS00001\",\n" +
//                "            \"TRACKOUT_PROCESS_CRR\":\"0\",\n" +
//                "            \"TRACKOUT_CRR_ID\":\"TS00001\",\n" +
//                "            \"MES_MAT_LIST\":[\n" +
//                "                {\n" +
//                "                    \"MES_RUN_HISTORY_ID\":333,\n" +
//                "                    \"MATERIAL_ID\":\"T1\",\n" +
//                "                    \"MATERIAL_TYPE\":\"4KUAISU1\",\n" +
//                "                    \"MATERIAL_NAME\":\"晶粒\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"MES_RUN_HISTORY_ID\":333,\n" +
//                "                    \"MATERIAL_ID\":\"T2\",\n" +
//                "                    \"MATERIAL_TYPE\":\"4KUAISU2\",\n" +
//                "                    \"MATERIAL_NAME\":\"焊条\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"MES_RUN_HISTORY_ID\":333,\n" +
//                "                    \"MATERIAL_ID\":\"T3\",\n" +
//                "                    \"MATERIAL_TYPE\":\"4KUAISU3\",\n" +
//                "                    \"MATERIAL_NAME\":\"环氧\"\n" +
//                "                }\n" +
//                "            ]\n" +
//                "        },\n" +
//                "        \"RETURN\":{\n" +
//                "            \"RETURNCODE\":\"0\",\n" +
//                "            \"RETURNMESSAGE\":\"\"\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
//                BaseEntity<LotIDInfoEntity> bean = (new Gson()).fromJson(ss, new TypeToken<BaseEntity<LotIDInfoEntity>>() {}.getType());
//                lotIDInfoEntity = bean.getData().getBody();
//                llWaferLayout.setVisibility(lotIDInfoEntity.getPROCESS().equals("P080") ? View.VISIBLE : View.GONE);
//                fillLotData();
//
//                tvEqpStatus.setText(lotIDInfoEntity.getEQP_RUN_STATE());//设备状态

        FreeUI_EntityCallBack<BaseEntity<LotIDInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<LotIDInfoEntity>>
                (new TypeToken<BaseEntity<LotIDInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<LotIDInfoEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), getSupportFragmentManager())) {

                    lotIDInfoEntity = response.body().getData().getBody();
                    llWaferLayout.setVisibility(lotIDInfoEntity.getPROCESS().equals("P080") ? View.VISIBLE : View.GONE);
                    fillLotData();

                    tvEqpStatus.setText(lotIDInfoEntity.getEQP_RUN_STATE());//设备状态
                    List<LotIDInfoEntity.LotIDSInfoEntity> MultiBatchStartLotids = lotIDInfoEntity.getEQP_RUN_LOTIDLIST();
                    lotIDList.clear();
                    if (MultiBatchStartLotids.size() > 0) {
                        for (LotIDInfoEntity.LotIDSInfoEntity entity : MultiBatchStartLotids) {
                            lotIDList.add(entity.getLOT_STATE() + "/" + entity.getLOT_ID());//拼接 批次状态/批次号
                            //showToast("获得多批信息："+lotIDList.size(),false);

                        }
                    } else {
                        //showToast("当前设备无已上线批次号",false);
                        //MultiBatchStartActivity.this.finish();// 关闭了窗体
                    }
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<LotIDInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDAGetEqpLotidInfo");//PDAGetEqpLotidInfo//PDAEQPInfo
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("EQP_ID", App.EQPID);
        jsonObject.addProperty("LOT_ID", lotID);
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDAGetEqpLotidInfo", jsonObject);//PDAGetEqpLotidInfo//PDAEQPInfo
    }


    /**
     * 提交
     */
    private void submit(String lotNum, String eqpNum, int adjustTrack) {
//        showToast("开始作业成功",true);
        //PDALotidTrankInEntity       JSONObject
        FreeUI_EntityCallBack<BaseEntity<PDALotidTrankInEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<PDALotidTrankInEntity>>
                (new TypeToken<BaseEntity<PDALotidTrankInEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<PDALotidTrankInEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), getSupportFragmentManager())) {
//                    showToast("开始作业成功", true);
                    //================================================
                    tvEqpStatus.setText(response.body().getData().getBody().getEQP_RUN_STATE());//设备状态
                    List<PDALotidTrankInEntity.TrankinLotIDListEntity> MultiBatchStartLotids = response.body().getData().getBody().getEQP_RUN_LOTIDLIST();
                    lotIDList.clear();
                    if (MultiBatchStartLotids.size() > 0) {
                        for (PDALotidTrankInEntity.TrankinLotIDListEntity entity : MultiBatchStartLotids) {
                            lotIDList.add(entity.getLOT_STATE() + "/" + entity.getLOT_ID());//拼接 批次状态/批次号
                            //showToast("获得多批信息："+lotIDList.size(),false);
                        }
                    } else {
                        //showToast("当前设备无已上线批次号",false);
                        //MultiBatchStartActivity.this.finish();// 关闭了窗体
                    }
                    //=========================================================
                    //showConfirmDialog(MultiBatchStartActivity.this,"开始作业成功");
//                    showToast("开始作业成功", false);
                    showConfirmDialog(MultiBatchStartActivity.this,response.body().getData().getReturn().getRETURNMESSAGE());
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<PDALotidTrankInEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDALotidTrankIn");////TrankIn
            }
        };
        List<WaferEntity> data = new ArrayList<>();
        if (adapter.getData().size() > 0){
            for (String str : adapter.getData()){
                data.add(new WaferEntity(str));
            }
        }
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("EQP_ID", App.EQPID);
        jsonObject.addProperty("LOT_ID", lotNum);
        jsonObject.addProperty("CRR_ID", tvProcess.getText().toString());
        jsonObject.addProperty("ADJUST_TRACK", adjustTrack);
        jsonObject.add("WaferIDList",new JsonParser().parse(new Gson().toJson(data)).getAsJsonArray());
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDALotidTrankIn", jsonObject);////TrankIn
    }

    @OnClick({R.id.lot_Ly, R.id.adjustable_But, R.id.replaceMateriel_But, R.id.process_Txt, R.id.tvLotID, R.id.flLotIDList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lot_Ly:
                if (App.EQPID.equals("")) {
                    showToast("设备信息为空", false);
                    return;
                }

                dialog = FreeApi_DialogUtils.getScanDialog(this, "请输入批号", s -> {
                    getLotInfo(s);
                    dialog.dismiss();
                });
                dialog.show(getSupportFragmentManager(), "END_DIALOG");
                break;
            case R.id.flLotIDList:
                if (App.EQPID.equals("")) {
                    showToast("设备信息为空", false);
                    return;
                }
                if (lotIDList.size() <= 0) {
                    showToast("未获取到多批信息", false);
                    return;
                }

//                if (lotIDPop != null) {
//                    if (lotIDPop.isShowing()) {
//                        lotIDPop.dismiss();
//                    }
                //} else {
                ////showToast("加载时批次："+lotIDList.size(),false);
                //flLotIDList.refreshDrawableState();
                //}
                lotIDPop = PopUtils.getNormalPop(getApplicationContext(), flLotIDList.getWidth(), lotIDList, ivLotIDListArrow, new StringCallback<NormalPopListAdapter>() {
                    @Override
                    public void onSelectorCallback(String val, int position) {
                        tvLotID.setText(val);
                        Onlotid = val.split("/")[1];
                        if (Onlotid.equals("")) {
                            //showToast("未获取到批次ID，请选择未进站批次", false);
                            //return;
                        } else {
                            getLotInfo(Onlotid);
                        }
                    }

                    FreeUI_GeneralFragmentDialog dialog;
                    @Override
                    public void onDeleteCallback(String val, NormalPopListAdapter adapter) {
                        dialog = getConfirmAndCancelDialog(MultiBatchStartActivity.this, "是否确认删除当前批次?", new FreeUI_CommonCallback() {
                            @Override
                            public void onSuccess() {
                                dialog.dismiss();
                                FreeUI_EntityCallBack<BaseEntity<JSONPObject>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<JSONPObject>>
                                        (new TypeToken<BaseEntity<JSONPObject>>() {
                                        }.getType(), getSupportFragmentManager(), this) {

                                    @Override
                                    public void onSuccess
                                            (final Response<BaseEntity<JSONPObject>> response) {
                                        if (response.body().isSuccess(getApplicationContext(), getSupportFragmentManager())) {
                                            lotIDList.remove(val);
                                            adapter.setNewData(lotIDList);
                                        }
                                    }

                                    @Override
                                    public void onError
                                            (Response<BaseEntity<JSONPObject>> response) {
                                        super.onError(response);
                                        loadError(response.getException(), "PDADeleteMesLotHis");
                                    }
                                };
                                JsonObject jsonObject = new JsonObject();
                                jsonObject.addProperty("EQP_ID", App.EQPID);
                                jsonObject.addProperty("OPERATOR", App.userEntity.getWORKNO());
                                jsonObject.addProperty("LOT_ID", val.split("/")[1]);
                                NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDADeleteMesLotHis", jsonObject);
                            }
                        }, new FreeUI_CommonCallback() {
                            @Override
                            public void onSuccess() {
                                dialog.dismiss();
                            }
                        });
                        dialog.show(getSupportFragmentManager(),"DELETE_DIALOG");
                    }
                });
                PopUtils.setArrowShow(ivLotIDListArrow);
                lotIDPop.showAsDropDown(flLotIDList, 0, 0);


                break;
            case R.id.adjustable_But:
                materielRv.setVisibility(materielRv.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                btnAdjustable.setText(materielRv.getVisibility() == View.VISIBLE ? "收起" : "展开");
                break;
            case R.id.replaceMateriel_But:
                FreeApi_Utils.skipWithExtraIntent("header", MultiBatchStartActivity.this, ReplaceMaterielActivity.class);
                break;
            case R.id.process_Txt:
                showSpanDialog(PROCESS_CRR, "请输入或扫描运输筐号");
                break;
        }
    }

    public class WaferEntity implements Serializable{
        private String WaferValue;

        public WaferEntity(String waferValue) {
            WaferValue = waferValue;
        }

        public String getWaferValue() {
            return WaferValue == null ? "" : WaferValue;
        }

        public void setWaferValue(String waferValue) {
            WaferValue = waferValue;
        }
    }

}